#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <memory>
#include <vector>
#include <algorithm>
#include <mutex>
#include <condition_variable>
#include "Redis.h"
#include "Command.h"
#include "Paraser.h"

using namespace std;



shared_ptr<Redis> redis;

extern condition_variable cv;
extern mutex mtx;

int StartServer(int argc, char **argv) {
    {
        lock_guard<mutex> lock(mtx);

        //cout << "Logs from your program will appear here!\n";
        //解析命令行参数
        std::vector<std::string> args;
        // 遍历所有命令行参数
        for (int i = 1; i < argc; ++i) {
            // 将每个参数转换为std::string，并添加到args向量中
            args.push_back(std::string(argv[i]));
        }
        auto it=find(args.begin(),args.end(),"--replicaof");
        if(it!=args.end()){
            redis=make_shared<RedisSlave>();
        }else{
            redis=make_shared<RedisMaster>();
        }

        for(int i=0;i<args.size();i++){
            if(args[i]=="--port"){
                if(i+1>=args.size()){
                cerr<<"--port must be followed by a port number"<<endl;
                return -1;
                }
                redis->port=std::stoi(args[i+1]);
            }else if(args[i]=="--replicaof"){
                if(i+2>=args.size()){
                cerr<<"--replicaof must be followed by a host and a port number"<<endl;
                return -1;
                }
                RedisSlave *slave=dynamic_cast<RedisSlave*>(redis.get());
                if(slave==nullptr){
                    cerr<<"--replicaof can only be used in slave mode"<<endl;
                    return -1;
                }
                slave->master_ip=args[i+1];
                slave->master_port=std::stoi(args[i+2]);
            }
            //cout<<"args["<<i<<"]="<<args[i]<<endl;
        }
        redis->init();
        //cout<<"Server started on port "<<redis->port<<endl;
        cv.notify_all();
    }

    redis->run();


    return 0;
}
